<template>
  <main
    class="w-full min-h-screen bg-gradient-to-br from-indigo-500 via-blue-400 to-purple-300 overflow-x-hidden relative">
    <!-- 粒子动画背景 -->
    <!-- <div class="absolute inset-0 pointer-events-none z-0">
      <canvas id="particles-bg" class="w-full h-full"></canvas>
    </div> -->
    <ParticleHeader />
    <!-- 顶部 Banner -->
    <section class="relative z-10 flex flex-col lg:flex-row items-center justify-between py-20 px-4 lg:px-24">
      <div class="flex-1 text-center lg:text-left animate-fade-in-up">
        <h1 class="text-5xl lg:text-7xl font-extrabold text-white drop-shadow-2xl mb-6 animate-gradient-text">{{
          pageData?.banner?.companyName }}</h1>
        <p class="text-xl lg:text-2xl text-white/80 mb-10 animate-fade-in">{{ pageData?.banner?.slogan }}</p>
        <LazyAppButton class="shadow-xl animate-pulse scale-110 hover:scale-125 transition-transform mb-6">立即咨询
        </LazyAppButton>
      </div>
      <img :src="pageData?.banner?.logo" alt="logo"
        class="w-33 h-33 lg:w-42 lg:h-42 rounded-full shadow-2xl animate-rotate-slow border-8 border-white/33" />
    </section>
    <!-- 波浪分割 -->
    <svg class="w-full h-16 lg:h-24 -mt-8 lg:-mt-16" viewBox="0 0 1440 320">
      <path fill="#fff" fill-opacity="1"
        d="M0,224L48,213.3C96,203,192,181,288,192C384,203,480,245,576,240C672,235,768,181,864,176C960,171,1056,213,1152,229.3C1248,245,1344,235,1392,229.3L1440,224L1440,320L1392,320C1344,320,1248,320,1152,320C1056,320,960,320,864,320C768,320,672,320,576,320C480,320,384,320,288,320C192,320,96,320,48,320L0,320Z">
      </path>
    </svg>
    <!-- 服务楼层 -->
    <section class="relative z-10 py-16 px-4 lg:px-24 bg-white animate-fade-in-up">
      <h2 class="text-4xl font-bold text-center text-indigo-600 mb-12 animate-fade-in">核心服务</h2>
      <div class="grid grid-cols-1 lg:grid-cols-3 gap-10" v-if="pageData?.services && pageData.services.length">
        <LazyAppCard v-for="item in pageData?.services" :key="item.title" :title="item.title"
          class="group hover:scale-105 hover:shadow-2xl transition-all duration-300 animate-fade-in-up">
          <div class="flex flex-col items-center">
            <div :class="item.iconBg"
              class="w-16 h-16 flex items-center justify-center rounded-full mb-4 animate-bounce">
              <span :class="item.icon" class="text-3xl"></span>
            </div>
            <p class="text-gray-600 text-center">{{ item.description }}</p>
          </div>
        </LazyAppCard>
      </div>
    </section>
    <!-- 曲线分割 -->
    <svg class="w-full h-16 lg:h-24 -mb-8 lg:-mb-16" viewBox="0 0 1440 320">
      <path fill="#f3f4f6" fill-opacity="1"
        d="M0,160L48,170.7C96,181,192,203,288,197.3C384,192,480,160,576,165.3C672,171,768,213,864,229.3C960,245,1056,235,1152,218.7C1248,203,1344,181,1392,170.7L1440,160L1440,320L1392,320C1344,320,1248,320,1152,320C1056,320,960,320,864,320C768,320,672,320,576,320C480,320,384,320,288,320C192,320,96,320,48,320L0,320Z">
      </path>
    </svg>
    <!-- 案例楼层 -->
    <section class="relative z-10 py-16 px-4 lg:px-24 bg-gray-50 animate-fade-in-up">
      <h2 class="text-4xl font-bold text-center text-indigo-600 mb-12 animate-fade-in">客户案例</h2>
      <div class="flex flex-wrap justify-center gap-10" v-if="pageData?.cases && pageData.cases.length">
        <LazyAppCard v-for="item in pageData?.cases" :key="item.title" :title="item.title"
          class="w-80 hover:shadow-indigo-200 hover:scale-105 transition-all animate-fade-in-up">
          <img :src="item.image" class="rounded-lg mb-4 w-full h-40 object-cover animate-slide-in" />
          <p class="text-gray-600">{{ item.description }}</p>
        </LazyAppCard>
      </div>
    </section>
    <!-- 团队楼层 -->
    <section class="relative z-10 py-16 px-4 lg:px-24 bg-white animate-fade-in-up">
      <h2 class="text-4xl font-bold text-center text-indigo-600 mb-12 animate-fade-in">核心团队</h2>
      <div class="flex flex-wrap justify-center gap-10" v-if="pageData?.team && pageData.team.length">
        <LazyAppCard v-for="item in pageData?.team" :key="item.name" :title="item.name"
          class="w-72 hover:scale-105 hover:shadow-xl transition-all animate-fade-in-up">
          <img :src="item.avatar"
            class="rounded-full w-20 h-20 mx-auto mb-4 border-4 border-indigo-100 animate-rotate-slow" />
          <p class="text-gray-600 text-center">{{ item.role }}</p>
        </LazyAppCard>
      </div>
    </section>
    <!-- 合作伙伴楼层 -->
    <section class="relative z-10 py-10 px-4 lg:px-24 bg-gray-50 animate-fade-in-up">
      <h2 class="text-4xl font-bold text-center text-indigo-600 mb-12 animate-fade-in">合作伙伴</h2>
      <div class="flex flex-wrap justify-center gap-8" v-if="pageData?.partners && pageData.partners.length">
        <img v-for="n in pageData?.partners" :key="n" :src="`https://api.dicebear.com/8.x/shapes/svg?seed=${n}`"
          class="w-24 h-24 rounded-full shadow-lg hover:scale-110 transition-transform animate-fade-in" />
      </div>
    </section>
    <!-- 联系我们楼层 -->
    <section class="relative z-10 py-16 px-4 lg:px-24 bg-white animate-fade-in-up">
      <h2 class="text-4xl font-bold text-center text-indigo-600 mb-12 animate-fade-in">联系我们</h2>
      <div class="max-w-xl mx-auto bg-indigo-50 rounded-lg p-10 shadow-2xl animate-fade-in">
        <div class="flex flex-col gap-6">
          <input class="p-4 rounded border focus:ring-2 focus:ring-indigo-400" placeholder="您的姓名"
            v-model="formData.name" />
          <input class="p-4 rounded border focus:ring-2 focus:ring-indigo-400" placeholder="联系方式"
            v-model="formData.contactInfo" />
          <textarea class="p-4 rounded border focus:ring-2 focus:ring-indigo-400" placeholder="您的需求"
            v-model="formData.requirements"></textarea>
          <LazyAppButton class="w-full animate-pulse" @click.stop="handleSubmit">提交</LazyAppButton>
        </div>
      </div>
    </section>
    <!-- <button @click="showModal" class="px-4 py-2 bg-purple-500 text-white rounded hover:bg-purple-600">
        通过插件显示Modal
      </button> -->
  </main>
</template>

<script setup lang="ts">
const { getHomeData, contactSubmit } = useHomeApi()
const { $toast, $modal } = useNuxtApp()
import ParticleHeader from '~/components/ParticleHeader.vue'


const pageData = ref()
const isLoading = ref(false)
const error = ref()

const formData = ref({
  name: '',
  contactInfo: '',
  requirements: ''
})

const submitResult = ref()
const errors = ref<Record<string, string>>({}) // 存储错误信息

definePageMeta({
  layout: 'default',
  showHeader: true
});

// 验证规则
const validateForm = () => {
  errors.value = {} // 清空之前的错误

  if (!formData.value.name.trim()) {
    errors.value.name = '姓名不能为空'
  }

  if (!formData.value.contactInfo.trim()) {
    errors.value.contactInfo = '联系方式不能为空'
  } else if (!/^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$|^1[3-9]\d{9}$/.test(formData.value.contactInfo)) {
    errors.value.contactInfo = '请输入有效的手机号'
  }

  if (!formData.value.requirements.trim()) {
    errors.value.requirements = '需求描述不能为空'
  }
  console.log('验证结果:', errors.value)

  return Object.keys(errors.value).length === 0 // 返回是否验证通过
}

const handleSubmit = async (event: MouseEvent | null) => {
  if (event) {
    event.preventDefault() // 阻止默认行为（如表单提交）
    event.stopPropagation() // 阻止事件冒泡
  }

  // 先进行表单验证
  if (!validateForm()) {
    submitResult.value = {
      success: false,
      message: '请检查表单填写是否正确'
    }
    return // 验证失败，直接返回
  }

  try {
    isLoading.value = true
    const response = await contactSubmit(formData.value)
    submitResult.value = {
      success: true,
      message: '提交成功！'
    }
    formData.value = { name: '', contactInfo: '', requirements: '' } // 清空表单
  } catch (error) {
    submitResult.value = {
      success: false,
      message: error instanceof Error ? error.message : '提交失败，请稍后再试'
    }
  } finally {
    isLoading.value = false
  }
}
// const services = [
//   { title: '数字化咨询', desc: '为企业量身定制数字化转型方案', icon: 'i-carbon-idea', iconBg: 'bg-indigo-100 text-indigo-600' },
//   { title: '系统开发', desc: '高性能企业级系统定制开发', icon: 'i-carbon-code', iconBg: 'bg-purple-100 text-purple-600' },
//   { title: '智能营销', desc: 'AI驱动的智能营销与数据分析', icon: 'i-carbon-ai', iconBg: 'bg-blue-100 text-blue-600' }
// ]
// const cases = [
//   { title: 'A集团数字化升级', desc: '为A集团打造一体化管理平台', img: 'https://images.unsplash.com/photo-1461749280684-dccba630e2f6?auto=format&fit=crop&w=400&q=80' },
//   { title: 'B企业智能营销', desc: '助力B企业实现精准获客', img: 'https://images.unsplash.com/photo-1506744038136-46273834b3fb?auto=format&fit=crop&w=400&q=80' }
// ]
// const teams = [
//   { name: '张总', role: 'CEO / 数字化专家', avatar: 'https://api.dicebear.com/8.x/avataaars/svg?seed=CEO' },
//   { name: '李工', role: 'CTO / 技术架构师', avatar: 'https://api.dicebear.com/8.x/avataaars/svg?seed=CTO' },
//   { name: '王经理', role: 'COO / 项目管理', avatar: 'https://api.dicebear.com/8.x/avataaars/svg?seed=COO' }
// ]


const showModal = () => {
  // 简单使用
  $modal.show({
    title: '提示',
    content: '确定要执行此操作吗?',
    showFooter: true,
    showCancelButton: true,
    showConfirmButton: true
  })

  // 或者使用confirm方法(返回Promise)
  $modal.confirm({
    title: '确认',
    content: '你确定要删除这个项目吗?',
  }).then((confirmed) => {
    if (confirmed) {
      // 用户点击了确认
    } else {
      // 用户点击了取消或关闭
    }
  })
}
// 粒子动画初始化
onMounted(async () => {
  try {
    isLoading.value = true
    pageData.value = await getHomeData()
    console.log('首页数据:', pageData.value)
    // $toast.success('获取成功!', { position: 'top-center' })
  } catch (err) {
    error.value = err
    $toast.error('获取失败!')

  } finally {
    isLoading.value = false
  }
  const canvas = document.getElementById('particles-bg') as HTMLCanvasElement
  if (!canvas) return
  const ctx = canvas.getContext('2d')!
  let w = canvas.width = window.innerWidth
  let h = canvas.height = window.innerHeight
  let particles = Array.from({ length: 60 }, () => ({
    x: Math.random() * w,
    y: Math.random() * h,
    r: Math.random() * 2 + 1,
    dx: (Math.random() - 0.5) * 0.8,
    dy: (Math.random() - 0.5) * 0.8,
    o: Math.random() * 0.5 + 0.3
  }))
  function draw() {
    ctx.clearRect(0, 0, w, h)
    for (const p of particles) {
      ctx.beginPath()
      ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2)
      ctx.fillStyle = `rgba(255,255,255,${p.o})`
      ctx.shadowColor = '#a5b4fc'
      ctx.shadowBlur = 12
      ctx.fill()
      p.x += p.dx
      p.y += p.dy
      if (p.x < 0 || p.x > w) p.dx *= -1
      if (p.y < 0 || p.y > h) p.dy *= -1
    }
    requestAnimationFrame(draw)
  }
  draw()
  window.addEventListener('resize', () => {
    w = canvas.width = window.innerWidth
    h = canvas.height = window.innerHeight
  })
})
</script>

<style scoped>
@keyframes fade-in-up {
  0% {
    opacity: 0;
    transform: translateY(40px);
  }

  100% {
    opacity: 1;
    transform: translateY(0);
  }
}

.animate-fade-in-up {
  animation: fade-in-up 1s cubic-bezier(.4, 0, .2, 1) both;
}

@keyframes fade-in {
  0% {
    opacity: 0;
  }

  100% {
    opacity: 1;
  }
}

.animate-fade-in {
  animation: fade-in 1.2s cubic-bezier(.4, 0, .2, 1) both;
}

@keyframes rotate-slow {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

.animate-rotate-slow {
  animation: rotate-slow 8s linear infinite;
}

@keyframes gradient-text {
  0% {
    background-position: 0% 50%;
  }

  100% {
    background-position: 100% 50%;
  }
}

.animate-gradient-text {
  background: linear-gradient(90deg, #fff 0%, #a5b4fc 50%, #fff 100%);
  background-size: 200% 200%;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  animation: gradient-text 3s linear infinite alternate;
}

@keyframes slide-in {
  0% {
    opacity: 0;
    transform: translateX(-40px);
  }

  100% {
    opacity: 1;
    transform: translateX(0);
  }
}

.animate-slide-in {
  animation: slide-in 1.2s cubic-bezier(.4, 0, .2, 1) both;
}
</style>